﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.ServiceModel;
using System.Transactions;
using System.Configuration;

[ServiceContract]
public interface IDetailMaintenance
{
    [OperationContract]
    [TransactionFlow(TransactionFlowOption.Allowed)]
    void InsertDetailRecord(int masterId, string title);
}
[ServiceBehavior(InstanceContextMode= InstanceContextMode.PerCall)]
public class DetailMaintenance : IDetailMaintenance
{
    [OperationBehavior(TransactionAutoComplete = true, TransactionScopeRequired = true)]
    public void InsertDetailRecord(int masterId, string title)
    {
        Console.WriteLine("Detail service inserting [{0}, {1}]", masterId, title);
        using (TransactionScope scope = new TransactionScope())
        {
            Console.WriteLine("\tLocal Txn Id [{0}]\n\tDist Txn Id [{1}]",
                Transaction.Current.TransactionInformation.LocalIdentifier,
                Transaction.Current.TransactionInformation.DistributedIdentifier);

            using (SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["detailConnectionString"]))
            {
                con.Open();
                using (SqlCommand com = new SqlCommand("insert Detailtable values (@master, @title)", con))
                {
                    com.Parameters.AddWithValue("@master", masterId);
                    com.Parameters.AddWithValue("@title", title);

                    com.ExecuteNonQuery();
                }
                con.Close();
            }
            scope.Complete();
        }
    }
}


class Program
{
    static void Main(string[] args)
    {
        ServiceHost host = new ServiceHost(typeof(DetailMaintenance));
        host.Open();
        Console.WriteLine("Detail Service is listening...");
        Console.ReadLine();
    }
}